package cn.ztydata.teachingsystem.heaven.web.controller;

import cn.ztydata.teachingsystem.exception.ServiceException;
import cn.ztydata.teachingsystem.exception.UploadException;
import cn.ztydata.teachingsystem.heaven.common.WebContext;
import cn.ztydata.teachingsystem.heaven.cons.Constants;
import cn.ztydata.teachingsystem.heaven.util.UploadUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 图片上传控制器类
 *
 * @author fanruiping
 * @since 2014-12-24
 */
@Controller
@RequestMapping("/file")
public class FileController extends BaseController{
    @Autowired
    private WebContext webContext;
    /**
     * 上传图片(markdown使用)
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-24
     */
    @RequestMapping(value = "/uploadImage",method = RequestMethod.POST)
    @ResponseBody
    public JsonNode uploadImage(@RequestParam("imageData") MultipartFile coverFile){
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode node = objectMapper.createObjectNode();

        //定义允许上传的图片类型
        List fileTypes = Lists.newArrayList("jpg", "png", "gif", "bmp");
        String url = null;

        try {
            //校验上传的文件
            UploadUtil.validateFile(coverFile, fileTypes);

            //保存上传的图片
            String saveDir = Constants.UPLOAD_DIR + "/" + "kpImg/";
            String fileExt = UploadUtil.getFileExt(coverFile.getOriginalFilename());
            url = saveDir + UploadUtil.generateFileName(fileExt);

            File file = new File(webContext.getRootDirPath(), url);
            FileUtils.writeByteArrayToFile(file, coverFile.getBytes());
        } catch (IOException ex) {
            log.debug("upload kp picture fail:return false");

            log.warn("知识点图片上传失败:url->" + url, ex);

            node.put("state",false);
            node.put("message","上传失败");

            return node;
        } catch (UploadException | ServiceException ex) {
            log.debug("catch UploadException|ServiceException:return false");

            node.put("state",false);
            node.put("message",ex.getMessage().isEmpty() ? "上传失败" : ex.getMessage());

            return node;
        }

        node.put("url", url);
        node.put("state","SUCCESS");

        log.debug("upload kp picture success:return true");

        return node;
    }

    /**
     * 上传图片（ueditor使用）
     * @param imageFile 图片表单
     * @return Map
     *
     * @author fanruiping
     * @since 2015-01-15
     */
    @RequestMapping(value = "/uploadImageForUedit",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> uploadImageForUedit(@RequestParam("imageData") MultipartFile imageFile) {
        //定义允许上传的图片类型
        List fileTypes = Lists.newArrayList("jpg","jpeg","png","gif","bmp");

        //定义结果
        Map<String, String> result = Maps.newHashMap();

        try {
            //校验上传的图片
            UploadUtil.validateFile(imageFile, fileTypes);

            //保存上传的图片
            String saveDir = Constants.UPLOAD_DIR + "/images/" + UploadUtil.generateFolderByDate() + "/";
            String fileExt = UploadUtil.getFileExt(imageFile.getOriginalFilename());
            String url = saveDir + UploadUtil.generateFileName(fileExt);

            File file = new File(webContext.getRootDirPath(), url);
            FileUtils.writeByteArrayToFile(file, imageFile.getBytes());

            result.put("state", "SUCCESS");
            result.put("url", url);

            return result;
        } catch(UploadException ex) {
            log.warn("校验图片失败:{}", ex.getMessage());

            result.put("state", "FAILED");
            return result;
        } catch (IOException e) {
            log.warn("上传图片发生IO异常");

            result.put("state", "FAILED");
            return result;
        }
    }
}
